<?php
namespace app\index\controller;
use app\common\controller\HomeBase;
use app\common\model\Article;
use app\common\model\ArticleCategory;
use app\common\model\Collect;
use app\common\model\SeoLog;
use think\facade\Cache;
use think\facade\Db;


class Job extends HomeBase
{
    protected $params;
    public function initialize()
    {

        parent::initialize();
        $params=$this->params;
        if (!isset($params['key'])||!$params['key']) {
            return fail('没有填写JobKey');
        }
        $otaConfig = sysconfig('key');
        if ($otaConfig['job_key'] != $params['key']) {
            return fail('JobKey不正确');
        }
    }

    //定时清理每月浏览量 每月1日0点执行
    public function clearMonthView()
    {
        (new Article())->where('id','>',0)
            ->save(['month_view'=>0]);
    }

    //定时清理每周浏览量 每周0点执行
    public function clearWeekView()
    {
        (new Article())->where('id','>',0)
            ->save(['week_view'=>0]);
    }
    //定时清理每周浏览量 每天0点执行
    public function clearDayView()
    {
        (new Article())->where('id','>',0)
            ->save(['day_view'=>0]);
    }
    //检测文章广告到期隐藏
    public function hideExpiredAdArticle()
    {
        $res=(new Article())
            ->where('is_ad',1)
            ->where('finish_time','<',time())
            ->save(['status'=>0]);
        if($res){
            return success('成功更新');
        }
    }

    //定时发布
    public function scheduledRelease()
    {
        $updatedAt=time();
        $prefix=env('database.PREFIX');
        $list=Db::query("select a.id from ".$prefix."article a inner join ".$prefix."article_attribute b  on a.id=b.article_id where a.status=0 and check_status =-1 and publish_time< ".$updatedAt." and publish_time>update_time;");
        $count=count($list);
        if($count) {
            $ids = array_column($list, 'id');
            $setField['status'] = 1;
            $setField['update_time'] = $updatedAt;
            (new Article())->whereIn('id', $ids)->save($setField);
            if (Cache::has('newArticle')) {
                Cache::delete('newArticle');
            }
        }
        return success('定时发布'.$count.'条');
    }

    //定时采集 采集官方的
    public function collect()
    {
        $data=$this->params;
        $page=isset($data['page'])?$data['page']:1;
        $where=[
            'site_name'=>$data['site_name'],
            'page'=>$page,
        ];
        $k = 0;
        for ($i=0;$i<=$page;$i++) {
            $result = getJsonData('Collect', 'list', $where, 0, 10);
            if (is_array($result) && $result['code'] == 1) {
                $result['code'] = 0;
                $list = $result['data'];
                foreach ($list as $v) {
                    $res = (new Collect())->download($v['uniquekey'], 'article');
                    if ($res !== false && $res == 0) {
                        $k++;
                    }
                }
            } else {
                return fail('获取列表失败');
            }
        }
        return success('采集到新的数据' . $k . '条');
    }



    //百度收录推送
    public function sendToBaidu()
    {
        return SeoLog::pushToBaidu('today');
    }



    public function createSitemap() {
        $site_url = (is_HTTPS() ? 'https://' : 'http://') . str_replace(':443','',$_SERVER['HTTP_HOST']);
        $str = '<?xml version="1.0" encoding="utf-8"?>'.PHP_EOL;
        $str .= '<urlset>'.PHP_EOL;
        $artNum=sysconfig('seo.article_sitemap_num');
        $articles = (New Article())->where('status',1)->order('id','desc')->limit($artNum?$artNum:100)->column('id,category_id,update_time');
        $i=0;
        $categorys = getJsonData('ArticleCategory', 'list');
        $cate = array_column($categorys, 'alias', 'id');
        foreach ($articles as $k => $v) {
            $url=Article::detailUrl($v['id'], $v['category_id'], $cate);
            $priority=($i<=10?'1.0':($i<=50?'0.8':'0.7'));
            $str .= '<url>';
            $str .= '<loc>'.$site_url.$url.'</loc>'.PHP_EOL;
            $str .= '<lastmod>'.date('Y-m-d H:i:s',$v['update_time']).'</lastmod>'.PHP_EOL;
            $str .= '<priority>'.$priority.'</priority >'.PHP_EOL;
            $str .= '<changefreq>daily</changefreq>'.PHP_EOL.PHP_EOL.PHP_EOL;
            $str .= '</url>';
            $i++;
        }

        $articles = (New ArticleCategory())->where('status',1)->order('sort','desc')
            ->order('id','asc')->column('id,alias,update_time');
        $i=0;
        foreach ($articles as $k => $v) {
            $url=Article::categoryUrl($v['id'], $cate);
            $priority=($i<=10?'1.0':($i<=50?'0.8':'0.7'));
            $str .= '<url>';
            $str .= '<loc>'.$site_url.$url.'</loc>'.PHP_EOL;
            $str .= '<lastmod>'.date('Y-m-d H:i:s',$v['update_time']).'</lastmod>'.PHP_EOL;
            $str .= '<priority>'.$priority.'</priority >'.PHP_EOL;
            $str .= '<changefreq>daily</changefreq>'.PHP_EOL.PHP_EOL.PHP_EOL;
            $str .= '</url>';
            $i++;
        }
        $str .='</urlset>'.PHP_EOL;
        file_put_contents(ROOT_PATH."public/sitemap.xml", $str);
        echo '网站地图更新成功！可以到网站根目录下的<a target="_blank" href="'.$site_url.'/sitemap.xml">sitemap.xml</a>查看！';
    }
}
